package com.tudouji.project.harvest.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.flow.service.process.service.impl.FlowProcessProxy;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.arealand.mapper.TArealandMapper;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.harvest.domain.Procurementcontract;
import com.tudouji.project.harvest.mapper.ProcurementcontractMapper;
import com.tudouji.project.harvest.service.IProcurementcontractService;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.organization.mapper.SupplierMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.service.impl.SalesspecificationServiceImpl;
import com.tudouji.project.quality.domain.Qamain;
import com.tudouji.project.quality.service.impl.QamainServiceImpl;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysDept;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.mapper.SysDeptMapper;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 合同管理Service业务层处理
 *
 * @author tudouji
 * @date 2021-04-07
 */
@Service
public class ProcurementcontractServiceImpl implements IProcurementcontractService, IFlowBaseService {
    @Autowired
    private ProcurementcontractMapper procurementcontractMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private SalespermissionServiceImpl permissionService;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private FlowProcessProxy flowProcessProxy;
    @Autowired
    private BusinesscodeServiceImpl codeService;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SalesspecificationServiceImpl salesspecificationService;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private TArealandMapper arealandMapper;
    @Autowired
    private QamainServiceImpl qamainService;
    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && com.tudouji.common.utils.StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 查询合同管理
     *
     * @param guid 合同管理ID
     * @return 合同管理
     */
    @Override
    public Procurementcontract selectProcurementcontractById(String guid) {
        return procurementcontractMapper.selectProcurementcontractById(guid);
    }

    /**
     * 查询合同管理列表
     *
     * @param procurementcontract 合同管理
     * @return 合同管理
     */
    @Override
    public List<Procurementcontract> selectProcurementcontractList(Procurementcontract procurementcontract, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (procurementcontract == null) {
            procurementcontract = new Procurementcontract();
        }
//        recharge.setFlowid("37");
        if (StringUtils.isNotBlank(status)) {
            // 待处理
            if (status.equals("00")) {
                startPage();
                procurementcontract.setCreateBy(sysUser.getUserId());
                return procurementcontractMapper.selectApplyPendingList(procurementcontract);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                procurementcontract.setStats(stss);
            }
        }
        //查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            return procurementcontractMapper.selectProcurementcontractList(procurementcontract);
        } else {
            procurementcontract.setCreateBy(sysUser.getUserId());
            //是否有部门权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "2");

            startPage();
            if (permissions.size() > 0) {
                String[] deptids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    deptids[i] = permissions.get(i).getDepartid();
                }
                procurementcontract.setDeptIds(deptids);
                return procurementcontractMapper.selectApplyListByPerm(procurementcontract);
            } else {
                //查询个人的
                return procurementcontractMapper.selectApplyListByUser(procurementcontract);
            }
        }
    }

    /**
     * 新增合同管理
     *
     * @param procurementcontract 合同管理
     * @return 结果
     */
    @Override
    public int insertProcurementcontract(Procurementcontract procurementcontract) {
        return procurementcontractMapper.insertProcurementcontract(procurementcontract);
    }

    /**
     * 修改合同管理
     *
     * @param procurementcontract 合同管理
     * @return 结果
     */
    @Override
    public int updateProcurementcontract(Procurementcontract procurementcontract) {
        return procurementcontractMapper.updateProcurementcontract(procurementcontract);
    }

    /**
     * 批量删除合同管理
     *
     * @param guids 需要删除的合同管理ID
     * @return 结果
     */
    @Override
    public int deleteProcurementcontractByIds(String[] guids) {
        return procurementcontractMapper.deleteProcurementcontractByIds(guids);
    }

    /**
     * 删除合同管理信息
     *
     * @param guid 合同管理ID
     * @return 结果
     */
    @Override
    public int deleteProcurementcontractById(String guid) {
        return procurementcontractMapper.deleteProcurementcontractById(guid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Procurementcontract contract, String fileIds, Long taskid, String opinion) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Procurementcontract pct = procurementcontractMapper.selectProcurementcontractByName(contract.getName());
        String guid;
        Organization org = organizationMapper.selectOrganizationByAutoId(contract.getOrgId());
        SysDept sysDept = deptMapper.selectDeptById(contract.getDeptId());
        Salesspecification spe = salesspecificationService.getBaseMatril(contract.getProductguid());
        Qamain qamain = qamainService.selectQamainById(contract.getQamainid());
        Supplier supplier = supplierMapper.selectSupplierById(contract.getSupplierId());
        // 获取库房
        Storeroom sr = storeroomMapper.selectStoreroomByGuid(contract.getSrguid());
        if (spe == null) {
            return AjaxResult.error("noBaseFlag");
        }
        if (null == contract.getId()) {
            if (pct != null) {
                return AjaxResult.error("合同重名！");
            }
            contract.setStrid(sr.getId());
            contract.setOrganizationid(org.getGuid());
            contract.setDepartid(sysDept.getGuid());
            contract.setDepartname(sysDept.getDeptName());
            if (supplier != null) {
                contract.setPartb(supplier.getUserid());
            }
            contract.setType(qamain.getType());
            contract.setParta(org.getName());
            contract.setStatus(-1);
            contract.setCode(codeService.getCode("20"));
            contract.setSpguid(spe.getGuid());
            contract.setStockunit("吨");
            guid = IdUtils.fastSimpleUUID();
            contract.setGuid(guid);
            contract.setCreateBy(sysUser.getUserId());
            contract.setOperatorid(sysUser.getGuid());
            contract.setFlowid("39");
            procurementcontractMapper.insertProcurementcontract(contract);
            FlowResult result = flowProcessProxy.start(processUtils.getStartNode(Long.valueOf(contract.getFlowid())), contract, fileIds, sysUser);
            if (result.getMsg().equals(ResultParam.SUCCESS)) {
                Procurementcontract pc = new Procurementcontract();
                pc.setStatus(result.getNextStat());
                pc.setGuid(guid);
                this.updateProcurementcontract(pc);
                return AjaxResult.success();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error(result.getMsg());
            }

        } else {
            contract.setStrid(sr.getId());
            contract.setOrganizationid(org.getGuid());
            contract.setDepartid(sysDept.getGuid());
            contract.setDepartname(sysDept.getDeptName());
            if (supplier != null) {
                contract.setPartb(supplier.getUserid());
            }
            contract.setType(qamain.getType());
            contract.setParta(org.getName());
            contract.setSpguid(spe.getGuid());
            contract.setStockunit("吨");
            procurementcontractMapper.updateProcurementcontract(contract);

            FlowResult result = flowProcessProxy.approval(taskid, fileIds, opinion, contract
                    , sysUser);
            if (result.getMsg().equals(ResultParam.SUCCESS)) {
                Procurementcontract pb = new Procurementcontract();
                pb.setStatus(result.getNextStat());
                pb.setGuid(contract.getGuid());
                this.updateProcurementcontract(pb);
                return AjaxResult.success();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error(result.getMsg());
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, Long taskid, String opinion, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Procurementcontract contract = procurementcontractMapper.selectProcurementcontractByNewId(id);

        FlowResult result = flowProcessProxy.approval(taskid, fileIds, opinion, contract
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Procurementcontract pb = new Procurementcontract();
            pb.setStatus(result.getNextStat());
            pb.setGuid(contract.getGuid());
            this.updateProcurementcontract(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult finance(Long id, Long taskid, String opinion, String fileIds, Procurementcontract entity) {
        if (id != null) {
            entity.setId(id);
            procurementcontractMapper.updateProcurementcontract(entity);
        }
        return approval(id, taskid, fileIds, opinion);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult finish(Long id) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Procurementcontract pb = new Procurementcontract();
        pb.setStatus(105);
        pb.setId(id);
        pb.setUpdateTime(DateUtils.getNowDate());
        pb.setUpdateBy(sysUser.getUserId());
        this.updateProcurementcontract(pb);
        return AjaxResult.success();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        Procurementcontract contract = procurementcontractMapper.selectProcurementcontractByNewId(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        FlowResult result = flowProcessProxy.refuse(taskid, fileIds, opinion, contract
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Procurementcontract pb = new Procurementcontract();
            pb.setStatus(result.getNextStat());
            pb.setGuid(contract.getGuid());
            this.updateProcurementcontract(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult del(Long id) {
        Procurementcontract apply = procurementcontractMapper.selectProcurementcontractByNewId(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        Procurementcontract contract = new Procurementcontract();
        contract.setId(id);
        contract.setStatus(0);
        procurementcontractMapper.updateProcurementcontract(contract);
        //更新待处理任务
        processUtils.updateTaskByOrderId(id, sysUser, Long.valueOf(apply.getFlowid()));
        return AjaxResult.success();
    }

    @Override
    public BasePojo getBaseById(Long id) {
        return procurementcontractMapper.selectProcurementcontractByNewId(id);
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return null;
    }
}
